package com.mokairui.threadpool.juc.exchanger;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Exchanger;

/**
 * @Description 当两个线程执行完, 交换互相的结果
 * @Author Mokairui
 * @Since 2021/11/6
 */
@Slf4j(topic = "c.Exchanger")
public class ExchangerDemo {
    public static void main(String[] args) {
        Exchanger<String> exchanger = new Exchanger<>();
        Girl girl = new Girl(exchanger);
        Boy boy = new Boy(exchanger);
        girl.start();
        boy.start();
    }

    static class Boy extends Thread {
        Exchanger<String> exchanger;

        public Boy(Exchanger exchanger) {
            this.exchanger = exchanger;
        }

        @Override
        public void run() {
            try {
                log.debug("男孩开始做好自己的定情信物: 同心🔒");
                // 交换互相的定情信物
                String rs = exchanger.exchange("同心🔒");
                log.debug("男孩收到礼物: {}", rs);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class Girl extends Thread {
        Exchanger<String> exchanger;

        public Girl(Exchanger exchanger) {
            this.exchanger = exchanger;
        }

        @Override
        public void run() {
            try {
                log.debug("女孩开始做好自己的定情信物: 钥匙🔑");
                // 交换互相的定情信物
                String rs = exchanger.exchange("钥匙🔑");
                log.debug("女孩收到礼物: {}", rs);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
